package com.beta.auth.utils;

import cn.hutool.poi.word.WordUtil;
import com.beta.auth.constants.BusinessConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * <p>Pro.UserCenter/com.beta.auth.utils.ResponseUtils</p>
 *
 * @description Response工具类
 * @author: zdwang
 * @date 2021/12/10 16:31
 */
@Slf4j
public class ResponseUtils {

    private ResponseUtils() {
    }

    /**
     * 错误页面打印
     *
     * @param response
     * @param
     */
    public static void printPage(HttpServletResponse response, String pageContent) {
        // 设置资源格式和编码
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(pageContent);
            // 强制将缓冲区中的数据发送出去,不必等到缓冲区满
            out.flush();
        } catch (IOException e) {
            log.error("错误页面打印异常：{}", e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     *
     */
    public static void toErrPage(String errmsg, String errcode, HttpServletResponse response) {
        String htmlStr = readFileByLines().replace("<% =ErrorMsg%>", errmsg).replace("<% =ErrorCode%>", errcode);
        // 跳转错误页面
        printPage(response, htmlStr);
    }

    /**
     * 读取html模板
     *
     * @return
     */
    public static String readFileByLines() {
        StringBuilder result = new StringBuilder();
        String tempString;
        try (InputStream inputStream = WordUtil.class.getClassLoader().getResourceAsStream("static/ErrorPage.html");
             InputStreamReader fileReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(fileReader)) {
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                result.append(tempString);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return result.toString();
    }

    public static void sendRedirect(HttpServletResponse response, String[] safeHosts, String url) {
        if (StringUtils.startsWithAny(url, safeHosts)) {
            try {
                response.sendRedirect(url);
            } catch (IOException e) {
                log.error("重定向异常，url = {}，异常：{}", url, e.getMessage(), e);
            }
        } else {
            log.warn("重定向地址非法：url = {}, safeHosts = {}", url, ArrayUtils.toString(url));
            ResponseUtils.toErrPage(BusinessConstants.SYSTEM_ERROR_MSG, BusinessConstants.PARAMS_ERROR_CODE,response);
        }
    }
}
